/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package Model;

import javax.microedition.rms.*;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.util.Calendar;
import java.util.TimeZone;
/**
 *
 * @author sergey
 */
public class CModel {

    public CRecord[] m_Records;
    public CCurrency[] m_Curencies;
    public CCategory[] m_Categories;

    public CModel()
    {
        m_Records = new CRecord[0];
        m_Curencies = new CCurrency[]{new CCurrency()};
        m_Categories = new CCategory[0];
    }

    public void ClearAllRecords()
    {
        m_Records = new CRecord[0];
    }

    public void AddRecord(CRecord rec)
    {
        int sz = m_Records.length;
        CRecord recs[] = new CRecord[sz +1];
        for (int i = 0; i < sz; ++i)
            recs[i] = m_Records[i];
        recs[sz] = rec;
        m_Records = recs;
        SortRecords();
    }

    public void AddCategory(CCategory cat)
    {
        int sz = m_Categories.length;
        CCategory cats[] = new CCategory[sz + 1];
        for (int i = 0; i < sz; ++i)
            cats[i] = m_Categories[i];
        cats[sz] = cat;
        m_Categories = cats;
    }

    public void RemoveCategory(CCategory cat)
    {
        {
            // Выдалім усе запісы з даннай катэгорыяй
            int rec_count = 0;
            for (int i =0; i < m_Records.length; ++i)
                if (m_Records[i].m_category == cat)
                    rec_count++;
            CRecord[] newRecords = new CRecord[m_Records.length - rec_count];

            int j=0;
            for (int i =0; i < m_Records.length; ++i)
            {
                if (m_Records[i].m_category != cat)
                {
                    newRecords[j] = m_Records[i];
                    j++;
                }
            }
            m_Records = newRecords;
        }

        int sz = m_Categories.length;
        CCategory cats[] = new CCategory[sz - 1];
        int j =0;
        for (int i = 0; i < sz; ++i)
        {
            if (cat != m_Categories[i])
            {
                cats[j] = m_Categories[i];
                j++;
            }
        }
        m_Categories = cats;
    }

    public void RemoveRecord(CRecord rec)
    {
        int sz = m_Records.length;
        CRecord recs[] = new CRecord[sz - 1];
        int j =0;
        for (int i = 0; i < sz; ++i)
        {
            if (rec != m_Records[i])
            {
                recs[j] = m_Records[i];
                j++;
            }
        }
        m_Records = recs;
    }

    public void SortRecords()
    {
        for (int i =0; i < m_Records.length; ++i)
            for (int j =0; j < m_Records.length; ++j)
            {
                if (m_Records[i].m_date.getTime() > m_Records[j].m_date.getTime())
                {
                    CRecord tmp = m_Records[i];
                    m_Records[i] = m_Records[j];
                    m_Records[j] = tmp;
                }
            }
    }
    // Удалить записи из RMS перед сохранением
    private void DeleteRecords(String name)
    {
       try
        {
            RecordStore rs = RecordStore.openRecordStore(name, false);
            RecordEnumeration re = rs.enumerateRecords(null, null, false);
            while (re.hasNextElement())
            {
                rs.deleteRecord(re.nextRecordId());
            }
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }
    }

    private String idCategory = "CCategory";
    private String idCurency = "CCurency";
    private String idRecords = "CRecords";
    private String idFirstRun = "FirstRun";
    public void Save()
    {
        try
        {
            DeleteRecords(idCategory);
            DeleteRecords(idCurency);
            DeleteRecords(idRecords);
            DeleteRecords(idFirstRun);

            RecordStore firstrun_rs = RecordStore.openRecordStore(idFirstRun, true);
            RecordEnumeration firstrun_re = firstrun_rs.enumerateRecords(null, null, false);
            byte [] firstrun_data = new byte[1];
            firstrun_rs.addRecord(firstrun_data, 0, firstrun_data.length);

            {
                ByteArrayOutputStream oStream = new ByteArrayOutputStream();
                DataOutputStream oDataStream = new DataOutputStream(oStream);
                oDataStream.writeInt(m_Categories.length);
                for (int i =0; i< m_Categories.length; ++i)
                {
                    byte [] arr = m_Categories[i].getBytes();
                    oDataStream.writeInt(arr.length);
                    if (arr.length > 0)
                        oDataStream.write(arr);
                }

                RecordStore rs = RecordStore.openRecordStore(idCategory, true);
                RecordEnumeration re = rs.enumerateRecords(null, null, false);
                byte [] data = oStream.toByteArray();
                rs.addRecord(data, 0, data.length);
                
            }
        
            {
                ByteArrayOutputStream oStream = new ByteArrayOutputStream();
                DataOutputStream oDataStream = new DataOutputStream(oStream);
                oDataStream.writeInt(m_Curencies.length);
                for (int i =0; i< m_Curencies.length; ++i)
                {
                    byte [] arr = m_Curencies[i].getBytes();
                    oDataStream.writeInt(arr.length);
                    if (arr.length > 0)
                        oDataStream.write(arr);
                }

                RecordStore rs = RecordStore.openRecordStore(idCurency, true);
                RecordEnumeration re = rs.enumerateRecords(null, null, false);
                byte [] data = oStream.toByteArray();
                rs.addRecord(data, 0, data.length);
            }

            {
                RecordStore rs = RecordStore.openRecordStore(idRecords, true);
                RecordEnumeration re = rs.enumerateRecords(null, null, false);
                for (int i =0; i < m_Records.length; ++i)
                {
                    byte[] data = m_Records[i].getBytes(m_Categories, m_Curencies);
                    rs.addRecord(data, 0, data.length);
                }
            }
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }

    }

    public void Load()
    {
        try
        {
            // При первом запуске категории просто посоздаём
            RecordStore firstrun_rs = RecordStore.openRecordStore(idFirstRun, true);
            RecordEnumeration firstrun_re = firstrun_rs.enumerateRecords(null, null, false);
            if (firstrun_re.numRecords() > 0)
            {
                RecordStore rs = RecordStore.openRecordStore(idCategory, true);
                RecordEnumeration re = rs.enumerateRecords(null, null, false);
                byte[] arr = re.nextRecord();
                ByteArrayInputStream inputStream = new ByteArrayInputStream(arr);
                DataInputStream inputDataStream = new DataInputStream(inputStream);

                int sz = inputDataStream.readInt();
                m_Categories = new CCategory[sz];
                for (int i =0; i < sz; ++i)
                {
                    m_Categories[i] = new CCategory();
                    int recsz = inputDataStream.readInt();
                    if (recsz > 0)
                    {
                        byte [] data = new byte[recsz];
                        inputDataStream.read(data);
                        m_Categories[i].fromBytes(data);
                    }
                }
            }
            else
            {
                m_Categories = new CCategory[]
                {
                    new CCategory("Іншае"),
                    new CCategory("Абеды"),
                    new CCategory("Прадукты"),
                    new CCategory("Машына"),
                    new CCategory("Тэлефон"),
                    new CCategory("Адпачынак"),
                    new CCategory("Падарункі"),
                    new CCategory("Дом/кватэра"),
                    new CCategory("Вопратка"),
                    new CCategory("Транспарт")
                };
            }

            {
                RecordStore rs = RecordStore.openRecordStore(idCurency, true);
                RecordEnumeration re = rs.enumerateRecords(null, null, false);
                if (re.numRecords() >0)
                {
                    byte[] arr = re.nextRecord();
                    ByteArrayInputStream inputStream = new ByteArrayInputStream(arr);
                    DataInputStream inputDataStream = new DataInputStream(inputStream);

                    int sz = inputDataStream.readInt();
                    m_Curencies = new CCurrency[sz];
                    for (int i =0; i < sz; ++i)
                    {
                        m_Curencies[i] = new CCurrency();
                        int recsz = inputDataStream.readInt();
                        if (recsz > 0)
                        {
                            byte [] data = new byte[recsz];
                            inputDataStream.read(data);
                            m_Curencies[i].fromBytes(data);
                        }
                    }
                }
                else
                {
                    m_Curencies = new CCurrency[]{new CCurrency()};
                }
            }

            {
                RecordStore rs = RecordStore.openRecordStore(idRecords, true);
                RecordEnumeration re = rs.enumerateRecords(null, null, false);
                m_Records = new CRecord[re.numRecords()];
                for (int i =0; i < re.numRecords(); ++i)
                {
                    byte[] data = re.nextRecord();
                    m_Records[i] = new CRecord(null, null, null, 0);
                    m_Records[i].fromBytes(data, m_Categories, m_Curencies);
                }
            }
            SortRecords();
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }
    }

    String GetOOString(String s)
    {
        if (s.length() == 1)
            return "0" + s;
        return s;
    }

    public String GetString()
    {
        String res = new String();
        for (int i =0; i < m_Records.length; ++i)
        {
            CRecord rec = m_Records[i];
            Calendar c = Calendar.getInstance();
            c.setTime(rec.m_date);
            res += GetOOString(Integer.toString(c.get(Calendar.DATE))) + "/" ;
            res += GetOOString(Integer.toString(c.get(Calendar.MONTH) + 1)) + "/" ;
            res += Integer.toString(c.get(Calendar.YEAR))+ " " ;
            res += GetOOString(Integer.toString(c.get(Calendar.HOUR_OF_DAY)))+ ":" ;
            res += GetOOString(Integer.toString(c.get(Calendar.MINUTE)))+ "," ;
            res += Integer.toString(rec.m_nAmount) + ",";
            res += rec.m_category.GetName() + ",";
            res += rec.m_Notes + "\n";
        }
        return res;
    }
}
